import asyncio
import base64
import json
import time
import os

msg = {
    "op": "publish",
    "topic": "/ubiquityrobot/pi_driver_node/button_event",
    "msg": {
        "type": 0,
        "value": 1
    }
}

save_file = {
    "op": "service_response",
    "service": "/ubiquityrobot/pi_driver_node/save_file_data",
    "values": {
        "result": "\u4fdd\u5b58\u6210\u529f"
    },
    "result": True,
    "id": "call_service:/ubiquityrobot/pi_driver_node/save_file_data:10"
}

file_list = {
    "op": "service_response",
    "service": "/ubiquityrobot/pi_driver_node/get_file_list",
    "values": {
        "files": [
        ],
        "dirs": [
        ],
        "current": "/home/pi/Lepi_Data/Scratch",
        "homedir": "/home/pi/Lepi_Data"
    },
    "result": True,
    "id": "call_service:/ubiquityrobot/pi_driver_node/get_file_list:14"
}

get_file = {
    "op": "service_response",
    "service": "/ubiquityrobot/pi_driver_node/get_file_data",
    "values": {
        "data": "UEsDBAo...."
    },
    "result": True,
    "id": "call_service:/ubiquityrobot/pi_driver_node/get_file_data:5"
}

baseDir = os.path.join(os.path.expanduser("~"),"Lepi_Data")

dirMap = {
    "sb3":"Scratch",
    "py":"Python",
    "sh":"Shell",
    "mp3":"Music",
    "wav":"Recording",
    "oga":"Recording",
    "png":"Photo",
    "jpg":"Photo",
    "nes":"nes",
    "zip-ml-image":"ros/learning_machine/image",
    "zip-ml-audio":"ros/learning_machine/audio",
    "zip-ml-pose":"ros/learning_machine/pose",
}

class File_IO:
    def __init__(self):
        pass

    def register(self, func_map):
        func_map['/ubiquityrobot/pi_driver_node/save_file_data'] = self.save_file_data
        func_map['/ubiquityrobot/pi_driver_node/get_file_list'] = self.get_file_list
        func_map['/ubiquityrobot/pi_driver_node/get_file_data'] = self.get_file_data

    async def save_file_data(self, ws, args, id):
        websocket = ws
        name = args['name']
        data = args['data']
        save_file['values'] = {"result": "保存成功"}
        save_file['id'] = f"call_service:/ubiquityrobot/pi_driver_node/save_file_data:{id}"
        ext = name.split('.')[-1]
        path = os.path.join(baseDir,dirMap[ext], name)
        path = path.replace('-ml-image','')
        path = path.replace('-ml-audio','')
        path = path.replace('-ml-pose','')

        with open(path,'wb') as f:
            head, data=data.split(",")
            f.write(base64.b64decode(data))
            # print(data)
        await websocket.send(json.dumps(save_file))
        if name == 'debug.sb3':
            await websocket.send(json.dumps(msg))

    async def get_file_data(self, ws, args, id):
        websocket = ws
        path = args['path'].replace('/home/pi', os.path.expanduser("~"))
        get_file['id'] = f"call_service:/ubiquityrobot/pi_driver_node/get_file_data:{id}"
        try:
            with open(path,'rb') as f:
                get_file['values']['data'] = base64.b64encode(f.read()).decode("ascii")
                # print(get_file)
                await websocket.send(json.dumps(get_file))
        except Exception as e:
            print(e)
    async def get_file_list(self, ws, args, id):
        websocket = ws
        dir = args['path'].replace('/home/pi', os.path.expanduser("~"))
        file_list['values']['files'] = []
        file_list['values']['dirs'] = []
        file_list['id'] = f"call_service:/ubiquityrobot/pi_driver_node/get_file_list:{id}"
        try:
            for i in os.scandir(dir):
                if i.is_dir():
                    file_list['values']['dirs'].append(i.name)
                else:
                    file_list['values']['files'].append(i.name)
        except Exception as e:
            print(e)
        await websocket.send(json.dumps(file_list))